import java.util.concurrent.atomic.AtomicInteger;

public class Demo_CAS {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(3);
        System.out.println(atomicInteger.incrementAndGet());
    }
    private boolean CAS(int address, int expectValue, int swapValue){
        if(address == expectValue){
            address = swapValue;
            return true;
        }
        return false;
    }

    //使用CAS模拟实现原子类方法
//    public int myIncrementAndGet(){
//        while(CAS(address, expectvalue, expectvalue + 1) != true){
//            expectValue = address;
//        }
//        return address;
//    }
}

//模拟实现自旋锁
class SpinLock{
    private Thread owner = null;
    private boolean CAS(Thread address, Thread expectValue, Thread swapValue){
        if(address == expectValue){
            address = swapValue;
            return true;
        }
        return false;
    }

    public void lock(){
        while(CAS(owner, null, Thread.currentThread()) != true){

        }
    }
    public void unlock(){
        owner = null;
    }
}

class Test{
    private int count = 0;
    public int countIncrease(){
        synchronized (this){
            for(int i = 0; i < 100; i++){
                count++;
            }
        }
        return count;
    }
}

